package main.java.com.lx.tools.trans

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.components.JBScrollPane
import main.java.com.lx.tools.utils.UIUtil
import java.awt.GridBagLayout
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.*


class ActionTrans : AnAction() {
    /**
     * 执行相关的动作
     */
    override fun actionPerformed(event: AnActionEvent?) {
        if (event == null) {
            return
        }
        val project = event.project ?: return
        val content = JPanel(GridBagLayout())
        val keyword = UIUtil.addTextInputToPanel("请输入要翻译的内容:", content)
        val zhToEn = JRadioButton("中译英", true)
        val enToZh = JRadioButton("英译中")
        content.add(zhToEn, ExternalSystemUiUtil.getLabelConstraints(0))
        content.add(enToZh, ExternalSystemUiUtil.getFillLineConstraints(0))
        val group = ButtonGroup()
        group.add(zhToEn)
        group.add(enToZh)
        val showResult = UIUtil.addTextInputToPanel("翻译结果为:", content)
        showResult.isEditable = false
        content.border = IdeBorderFactory.createEmptyBorder(0, 0, 8, 0)

        val getTransResult = {
            val query = keyword.text
            if (query.isNotBlank()) {
                var to = "zh"
                if (zhToEn.isSelected) {
                    to = "en"
                }
                showResult.text = TransApi.getTransResult(query, to)
            }
        }

        content.addKeyListener(object : KeyAdapter() {
            override fun keyPressed(e: KeyEvent) {
                if (e.keyCode == 10) {
                    getTransResult()
                }
            }
        })

        object : DialogWrapper(project) {
            init {
                title = "翻译工具"
                myOKAction.putValue("Name", "翻译")
                init()
            }

            override fun createCenterPanel(): JComponent? {
                return JBScrollPane(content)
            }

            override fun createActions(): Array<Action> {
                return arrayOf(okAction)
            }

            override fun doOKAction() {
                if (this.okAction.isEnabled) {
                    getTransResult()
                }
            }
        }.showAndGet()

    }


}